<template>
  <div class="organizerNewly">
    <div class="organizerNewly-left">
      <div class="organizer">
        <el-tree
          ref="organizerTree"
          v-loading="treeLoading"
          :data="organizerTree"
          :props="{}"
          node-key="id"
          default-expand-all
          draggable
          highlight-current
          :expand-on-click-node="false"
          :render-content="renderContent"
          @node-drop="handleDragEnd"
          @node-click="getDetailByNodeId"
          :allow-drop="allowDrop"
          :allow-drag="allowDrag"
        />
      </div>
    </div>
    <div class="organizerNewly-right">
      <div class="currentLevelInfo">
        <div class="currentLevelInfo-title">
          <div class="currentLevelInfo-title_left">
            <h4>
              {{ orgNodeInfo.orgName }}
              <el-button
                class="menu"
                size="mini"
                v-if="orgNodeInfo.orgType === 1"
                >集团</el-button
              >
              <el-button
                class="menu"
                size="mini"
                v-if="orgNodeInfo.orgType === 2"
                >公司</el-button
              >
              <el-button
                class="menu"
                size="mini"
                v-if="orgNodeInfo.orgType === 3"
                >部门</el-button
              >
              <el-button
                class="menu"
                size="mini"
                v-if="orgNodeInfo.orgType === 4"
                >岗位</el-button
              >
            </h4>
          </div>
          <div class="currentLevelInfo-title_right">
            <el-button
              type="primary"
              @click.stop="editNode()"
              class="el-icon-edit"
              v-if="
                (nodeValue && nodeValue.orgType !== 2 && showAddSubOrg) ||
                  (nodeValue && nodeValue.orgType === 1)
              "
              >编辑信息</el-button
            >
            <el-button
              type="primary"
              @click.stop="authorizationBtn()"
              v-if="nodeValue && nodeValue.orgType === 4 && showAddSubOrg"
              >权限设置</el-button
            >
          </div>
        </div>
        <p class="currentLevelInfo-summary" v-if="orgNodeInfo.orgDesc">
          描述：{{ orgNodeInfo.orgDesc }}
        </p>
        <div class="currentLevelInfo-relation">
          <p v-if="orgNodeInfo.parentId !== '0'">
            上级组织：{{ orgNodeInfo.parentOrganizationNameList }}
          </p>
          <p v-if="orgNodeInfo.orgType === 3 || orgNodeInfo.orgType === 4">
            所属公司：{{ orgNodeInfo.companyName }}
          </p>
          <p v-if="orgNodeInfo.orgType === 4">
            拥有角色：{{ orgNodeInfo.roleNameList }}
          </p>
        </div>
      </div>
      <div class="currentLevel-module">
        <div class="currentLevel-module_title">
          <div class="title-left">
            <h4>下级组织</h4>
          </div>
          <div class="title-right">
            <el-button
              type="primary"
              @click.stop="openDialogVisibleOrg()"
              icon="el-icon-plus"
              v-show="showAddSubOrg"
              >新增下级组织</el-button
            >
          </div>
        </div>
        <div
          class="currentLevel-module_content"
          v-if="nodeValue && nodeValue.children"
        >
          <div class="lowerLevelBox">
            <div class="lastOrg" v-if="!nodeValue.children.length">
              已到末级组织
            </div>
            <div
              class="lowerLevelBox-item"
              v-for="(item, index) in nodeValue.children"
              :key="index"
            >
              <div class="lowerLevelBox-item_title">
                <span class="orgName">{{ item.orgName }}</span>
                <el-button class="menu" size="mini" v-if="item.orgType === 1"
                  >集团</el-button
                >
                <el-button class="menu" size="mini" v-if="item.orgType === 2"
                  >公司</el-button
                >
                <el-button class="menu" size="mini" v-if="item.orgType === 3"
                  >部门</el-button
                >
                <el-button class="menu" size="mini" v-if="item.orgType === 4"
                  >岗位</el-button
                >
              </div>
              <div class="lowerLevelBox-item_arrow">
                <el-button
                  @click="subOrg(item)"
                  class="arrow"
                  size="mini"
                  icon="el-icon-arrow-right"
                ></el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="currentLevel-module">
        <div class="currentLevel-module_title">
          <div class="title-left">
            <h4>所属人员</h4>
          </div>
          <div class="title-right" v-if="nodeValue && nodeValue.orgType === 4">
            <el-button
              type="primary"
              @click.stop="addUserBtn()"
              icon="el-icon-plus"
              v-if="showAddSubOrg"
              >添加人员</el-button
            >
            <el-button
              type="primary"
              @click.stop="deleteUserBatch()"
              icon="el-icon-minus"
              v-if="showAddSubOrg"
              >移除</el-button
            >
          </div>
        </div>
        <el-editable
          class="el-table"
          :data="userListData"
          height="200"
          v-loading="tableLoading"
          :columns="userListColumns"
          @selection-change="handleSelectionChange"
        >
          <template slot="default-operate" slot-scope="scope">
            <el-button
              size="medium"
              @click.stop="deleteUser(scope)"
              type="text"
              v-if="showAddSubOrg"
              >移除</el-button
            >
          </template>
        </el-editable>
      </div>
    </div>
    <!-- 新增弹框 -->
    <el-dialog
      :title="!isEditUser ? '新增下级组织' : '修改下级组织'"
      :visible.sync="dialogVisibleOrg"
      class="dialog-box"
      width="35%"
      @close="resetForm"
    >
      <el-form
        ref="orgForm"
        :model="orgForm"
        inline
        label-width="110px"
        :rules="orgFormRules"
      >
        <el-form-item label="上级组织">
          <el-input
            v-model="orgForm.loginName"
            placeholder="请输入"
            clearable
            readonly
            maxlength="16"
          />
        </el-form-item>
        <el-form-item label="下级组织分类" prop="orgType">
          <el-select v-model="orgForm.orgType" placeholder="请选择">
            <el-option
              v-for="(item, index) in orgType"
              :key="index"
              :label="item.lab"
              :value="item.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="下级组织名称" prop="orgName">
          <el-input
            v-model="orgForm.orgName"
            placeholder="请输入下级组织名称"
            clearable
            maxlength="16"
          />
        </el-form-item>
        <el-form-item label="组织描述" prop="orgDesc">
          <el-input
            type="textarea"
            :rows="4"
            maxlength="200"
            v-model="orgForm.orgDesc"
            placeholder="请输入组织描述"
            clearable
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click.stop="dialogVisibleOrg = false">取消</el-button>
        <el-button
          type="primary"
          @click.stop="submitEditForm"
          :loading="addOrgLoading"
          >确定</el-button
        >
      </span>
    </el-dialog>
    <!-- 编辑组织/集团/岗位/部门 -->
    <edit-org ref="editOrg" @initial="initial"></edit-org>
    <!-- 添加人员 -->
    <add-user ref="addUser" @getUserList="getUserList"></add-user>
    <!-- 权限设置 -->
    <auth-set ref="authSet" @getDetailByNodeId="getDetailByNodeId"></auth-set>
  </div>
</template>
<script>
import ElEditable from '@components/el-editable/door/index.vue'
import addUser from '@/moduleComponents/orgainzationManagement/addUser.vue'
import editOrg from '@/moduleComponents/orgainzationManagement/editOrg.vue'
import authSet from '@/moduleComponents/orgainzationManagement/auth.vue'
import {
  getAllUcOrganization, // 组织树
  UcOrganizationDeleteById,
  UcOrganizationGetById,
  UcOrganizationUpdate,
  addOrganization,
  pageListByPosition, // 角色列表
  UcOrganizationUserList, // 岗位用户列表
  deletePositionUser, // 移除岗位员工
  deletePositionUserBatch, // 批量移除岗位员工
  sortOrganization // 拖拽排序
} from '@const/api_staffCenter.js'

import {orgType, userListColumns} from './const.js'
import {isNull, hasIn} from 'lodash'
export default {
  name: 'OrganizerNewly',
  components: {ElEditable, addUser, authSet, editOrg},
  data() {
    return {
      orgType,
      dialogVisibleOrg: false,
      organizerTree: [], // 组织结构树的数据
      treeLoading: false, // 树的Loading
      parentLoading: false, // 右侧详情
      parentForm: {
        orgName: '', // 组织名称
        orgCode: '', // 层级编码
        id: '', // orgId
        parentOrgId: '', // 父级id
        parentOrgName: '', // 父级名称
        orgDesc: '' // 组织描述
      },
      childForm: {
        orgName: '', // 组织名称
        orgCode: '', // 层级编码
        parentOrgId: '', // 父级id
        parentOrgName: '', // 父级名称
        orgDesc: '' // 组织描述
      },
      addOrgLoading: false, //添加组织的按钮
      // 新增下级组织表单项
      orgForm: {
        orgType: '', // 组织名称
        orgDesc: '', // 层级编码
        orgName: '', // orgId
        parentId: '' // 父级id
      },
      // 编辑新增下级组织的校验
      orgFormRules: {
        orgName: [
          {required: true, message: '请输入下级组织名称', trigger: 'blur'}
        ],
        orgDesc: [{message: '请输入描述信息', trigger: 'blur'}],
        orgType: [{required: true, message: '请选择分类', trigger: 'change'}]
      },
      nodeValue: null, // 选中的node节点
      orgNodeInfo: {}, // 集团、公司、组织、岗位信息
      bols: false, // 子节点的显示隐藏
      submitLoading: false, // 修改后保存的Loading
      addChildNodeLoading: false, // 增加后的Loading
      fbol: true, // 是否显示子节点的内容
      isEditUser: false,
      userListData: [], //所属人员
      userListColumns,
      tableLoading: false,
      readonly: true,
      curItemTreeData: {},
      role: {
        page: 1,
        pageSize: 20,
        roleName: '',
        orgId: '',
        data: []
      },
      multipleSelection: [],
      showAddSubOrg: false
    }
  },
  computed: {
    isdisabledFn() {
      return isNull(this.nodeValue)
    }
  },
  mounted() {
    this.initial()
  },
  methods: {
    changeTreeData(data, key) {
      data.children.forEach((item, index) => {
        if (key === item.id) {
          this.curItemTreeData = {
            preId: index === 0 ? 0 : data.children[index - 1].id
          }
        }
        if (item.children && item.children.length > 0) {
          this.changeTreeData(item, key)
        }
      })
    },
    // 可拖拽的树
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      if (this.organizerTree[0].children.length > 0) {
        this.changeTreeData(this.organizerTree[0], draggingNode.data.id)
      }
      if (dropType === 'before' || dropType === 'after') {
        let obj = {
          id: draggingNode.data.id,
          companyId: dropNode.data.companyId,
          parentId: dropNode.data.parentId,
          preId: this.curItemTreeData.preId
        }
        this.upDownNode(obj)
      } else {
        let obj = {
          id: draggingNode.data.id,
          companyId: dropNode.data.companyId,
          parentId: dropNode.data.value,
          preId: this.curItemTreeData.preId
        }
        this.upDownNode(obj)
      }
    },
    // // 上下移动节点
    upDownNode(dataObj) {
      this.treeLoading = true
      this.$axios({
        method: 'POST',
        url: sortOrganization,
        data: dataObj
      })
        .then(res => {
          this.$message({message: '移动成功', type: 'success'})
          this.initial()
        })
        .finally(() => {
          this.treeLoading = false
        })
    },
    // 拖拽时判定目标节点能否被放置
    allowDrop(draggingNode, dropNode, type) {
      if (draggingNode.data.orgType === 3) {
        if (
          dropNode.parent.data.orgType === 2 ||
          dropNode.parent.data.orgType === 3
        ) {
          return true
        }
      }
      if (draggingNode.data.orgType === 4) {
        if (
          dropNode.parent.data.orgType === 3 ||
          dropNode.parent.data.orgType === 4
        ) {
          return true
        }
      }
    },
    allowDrag(draggingNode, dropNode, type) {
      if (draggingNode.data.orgType === 1 || draggingNode.data.orgType === 2) {
        this.$message.error('集团、公司不能拖拽')
        return false
      } else {
        return true
      }
    },
    // 初始化页面
    initial() {
      this.treeLoading = true
      this.$axios({
        method: 'get',
        url: getAllUcOrganization
      })
        .then(res => {
          let data = hasIn(res, 'data.payload') ? [res.data.payload] : []
          this.orgNodeInfo = data[0][0]
          this.organizerTree = this.resetOrgTree(data[0])
          this.getUserList(data[0][0].id)
          this.getDetailByNodeId(data[0][0])
          this.$nextTick(() => {
            this.$refs.organizerTree.setCurrentKey(data[0][0].id)
          })
        })
        .finally(() => {
          this.treeLoading = false
        })
    },
    // 新增组织弹框
    openDialogVisibleOrg() {
      this.orgForm.parentId = this.nodeValue.id
      this.orgForm.loginName = this.nodeValue.orgName
      this.dialogVisibleOrg = true
    },
    submitEditForm() {
      this.$refs['orgForm'].validate(valid => {
        if (valid) {
          this.isEditUser ? this.updateOrg() : this.addOrg()
        } else {
          return false
        }
      })
    },
    addOrg() {
      this.addOrgLoading = true
      this.$axios({
        method: 'post',
        url: addOrganization,
        data: {
          ...this.orgForm
        }
      })
        .then(data => {
          this.$message({message: '新增成功', type: 'success'})
          this.initial()
          this.addOrgLoading = false
        })
        .finally(() => {
          this.addOrgLoading = false
          this.dialogVisibleOrg = false
        })
    },
    updateOrg() {},
    // 递归重构架构树
    resetOrgTree(list) {
      const getId = arr => {
        arr.forEach(item => {
          // 新建属性
          !item.label && (item.label = item.orgName)
          !item.value && (item.value = item.id)
          // 岗位
          item.positionNameAndUserNameList &&
            item.positionNameAndUserNameList.forEach(it => {
              it.label = it.positionUserName
              it.value = it.positionId
              it.isDuty = true
            })
          if (item.children && item.children.length) {
            getId(item.children)
          }
          !item.children && (item.children = [])
          item.children.push(...(item.positionNameAndUserNameList || []))
        })
      }
      getId(list)
      return list
    },
    // 可删除的树
    renderContent(h, {node, data, store}) {
      if (data.isDuty) {
        return (
          <span style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
            <span>
              <span>{node.label}</span>
            </span>
          </span>
        )
      } else {
        return (
          <span style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
            <span>
              <span>{node.label}</span>
            </span>
            <span>
              <div
                class="el-icon-error"
                style="font-size: 12px;margin-left:5px;"
                type="text"
                on-click={() => this.deleteNode(node, data)}
              />
            </span>
          </span>
        )
      }
    },
    deleteNode(node, data) {
      if (data.isDuty) {
        this.$message({type: 'warning', message: '不允许删除岗位'})
        return
      }
      this.$confirm('此操作将永久删除该节点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 如果删除的是已选中的按钮
          if (node.orgId === this.nodeValue.orgId) {
            this.nodeValue = null
          }
          this.$axios({
            method: 'POST',
            url: UcOrganizationDeleteById,
            data: {id: data.id}
          })
            .then(res => {
              this.$message({message: '删除成功', type: 'success'})
            })
            .finally(() => {
              this.initial()
              this.treeLoading = false
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 重置添加子节点的数据
    resetNextChildData() {
      this.$refs.childForm.resetFields()
    },
    // 点击获取节点
    getDetailByNodeId(node) {
      let storeId = this.$store.state.companyId
      if (storeId === 'null') {
        storeId = '-1'
      }
      if (node.companyId && node.companyId.toString() === storeId) {
        this.showAddSubOrg = true
      } else {
        this.showAddSubOrg = false
      }
      this.getUserList(node.id)
      if (node.isDuty) {
        return
      }
      this.nodeValue = node
      this.parentLoading = true
      this.$axios({
        url: `${UcOrganizationGetById}?id=${node.id}`,
        method: 'get'
      })
        .then(res => {
          let obj = hasIn(res, ['data', 'payload']) ? res.data.payload : {}
          obj.parentOrganizationNameList =
            obj.parentOrganizationNameList !== null
              ? obj.parentOrganizationNameList.join(' / ')
              : ''
          obj.roleNameList =
            obj.roleNameList !== null ? obj.roleNameList.join(' / ') : ''
          this.orgNodeInfo = obj
          for (let item in this.parentForm) {
            this.parentForm[item] = obj[item]
          }
        })
        .finally(() => {
          this.parentLoading = false
        })
    },
    // 新增内容按钮
    newChildNode(bols) {
      if (this.isdisabledFn) {
        this.$message({type: 'warning', message: '请先选择左侧的结构'})
        return
      }
      this.bols = true
      this.childForm.parentOrgName = this.parentForm.orgName
      // 返回的id为orgId，后端格式不规范
      this.childForm.parentOrgId = this.parentForm.id
    },
    // 修改的当前层级信息
    updataNode(fbol) {
      if (this.isdisabledFn) {
        this.$message({type: 'warning', message: '请先选择左侧组织'})
        return
      }
      this.fbol = !this.fbol
      this.submitLoading = true
      if (!this.parentForm.orgName) {
        this.$message({message: '层级名称不能为空', type: 'warning'})
        this.submitLoading = false
      } else {
        this.$axios({
          method: 'post',
          url: UcOrganizationUpdate,
          data: {
            id: this.nodeValue.orgId, // 节点的id
            orgName: this.parentForm.orgName, // 组织名称
            orgDesc: this.parentForm.orgDesc // 组织名称
          }
        })
          .then(res => {
            this.initial()
          })
          .finally(() => {
            this.submitLoading = false
          })
      }
    },
    // 子集信息
    addChildNode() {
      if (this.isdisabledFn) {
        this.$message({type: 'warning', message: '请先选择左侧组织'})
        return
      }
      this.bols = !this.bols
      this.addChildNodeLoading = true
      if (!this.childForm.orgName) {
        this.$message({message: '请填写层级名称', type: 'warning'})
        this.bols = !this.bols
        this.addChildNodeLoading = false
      } else {
        this.$axios({
          method: 'post',
          url: UcOrganizationSave,
          data: {
            orgName: this.childForm.orgName,
            parentOrgId: this.childForm.parentOrgId,
            orgDesc: this.childForm.orgDesc
          }
        })
          .then(res => {
            this.initial()
            // 重置数据
            this.resetNextChildData()
          })
          .finally(() => {
            this.addChildNodeLoading = false
          })
      }
    },
    // 权限设置
    authorizationBtn() {
      this.$refs.authSet.showDialog(this.nodeValue)
    },
    getUserList(orgId) {
      this.tableLoading = true
      this.$axios({
        method: 'get',
        url: `${UcOrganizationUserList}?relationStatus=1&orgId=${orgId}`
      })
        .then(res => {
          if (res.data.code === '0') {
            this.userListData = res.data.payload.content
          }
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
    addUserBtn() {
      this.$refs.addUser.showDialog(this.nodeValue)
    },
    // 移除岗位员工
    deleteUser(scope) {
      this.$confirm('此操作将移除所属人员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios({
          url: deletePositionUser,
          method: 'POST',
          data: {
            id: scope.row.id
          }
        })
          .then(res => {
            this.getUserList(this.nodeValue.id)
          })
          .finally(() => {})
      })
    },
    // 批量移除岗位员工
    deleteUserBatch() {
      if (!this.multipleSelection.length) {
        this.$message.error('请选择人员')
        return false
      }
      this.$confirm('此操作将移除所属人员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let idList = []
        this.multipleSelection.forEach(item => {
          idList.push(item.id)
        })
        this.$axios({
          url: deletePositionUserBatch,
          method: 'POST',
          data: {
            idList: idList
          }
        })
          .then(res => {
            this.$message({message: '删除成功', type: 'success'})
            this.getUserList(this.nodeValue.id)
          })
          .finally(() => {})
      })
    },
    editNode() {
      this.$refs.editOrg.showDialog(this.orgNodeInfo)
    },
    subOrg(item) {
      this.nodeValue = item
      this.orgNodeInfo = item
      this.$nextTick(() => {
        this.$refs.organizerTree.setCurrentKey(item.id)
        this.getDetailByNodeId(item)
      })
    },
    handleSelectionChange(data) {
      this.multipleSelection = data
    },
    resetForm() {
      this.$refs['orgForm'].resetFields()
    }
  }
}
</script>
<style lang="less" scoped type="text/less">
.organizerNewly {
  display: flex;

  .orgName {
    display: inline-block;
    min-width: 200px;
  }

  .lastOrg {
    padding: 30px 0;
    text-align: center;
  }

  .menu {
    background-color: rgba(73, 192, 175, 0.1);
    border-color: rgba(73, 192, 175, 0.2);
    color: #49c0af;
  }

  .organizerNewly-left {
    min-width: 220px;
    overflow: auto;
    padding: 20px 10px;
    box-sizing: border-box;
    border: 1px solid #e4e4e4;

    .organizerNewly-left-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .font-tip {
      font-size: 12px;
      margin-bottom: 10px;
      color: #dddfe1;
    }
  }

  .el-autocomplete {
    width: 211px;
  }
  // 重置文本框宽度
  .dialog-box {
    .el-textarea {
      width: 218px;
    }
  }
  .organizerNewly-right {
    margin-left: 10px;
    flex: 1;
    padding: 20px 10px;
    box-sizing: border-box;
    border: 1px solid #e4e4e4;
    overflow: scroll;
    .currentLevelInfo {
      margin-bottom: 40px;
      &-title {
        display: flex;
        justify-content: space-between;
        &_left {
          h4 {
            font-size: 20px;
          }
        }
      }
      &_summary {
        color: #606266;
      }
    }
    .currentLevel-module {
      margin: 20px 0;
      &_title {
        display: flex;
        justify-content: space-between;
        padding: 5px 10px;
      }
      &_content {
        .lowerLevelBox {
          border: 1px solid #ededed;
          &-item {
            display: flex;
            justify-content: space-between;
            border-bottom: 1px solid #ededed;
            padding: 10px 15px;
            &:last-child {
              border-bottom: none;
            }
          }
          .arrow {
            border: none;
            margin-right: 20px;
          }
        }
      }
    }
  }
}
</style>
